import fetch from 'isomorphic-fetch';
import querystring from "querystring";
//登录
export const LOGIN_REQUEST = 'LOGIN_REQUEST';//发送登录信息
export const LOGIN_RECEIVE = 'LOGIN_RECEIVE';//处理登录信息
//登出
export const LOGOUT = 'LOGOUT';
const headers = new Headers({
    "Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8',
    "Accept": 'application/json, text/javascript, */*; q=0.01',
    "Origin": '*',
    "Access-Control-Allow-Origin": '*'
});

export function action_login ( user ) {
    return (dispatch, getState) => {
        if(should_login(getState(), user)) {
            return dispatch(fetch_login(user))
        }
    }
}

function login_request ( user ) {
    return {
        type: LOGIN_REQUEST,
        user
    }
}

function login_receive ( user, json ) {
    return {
        type: LOGIN_RECEIVE,
        user,
        isLogin: json.status
    }
}

function fetch_login (user) {
    return dispatch => {
        dispatch(login_request( user));
        return fetch(`/home/users/login`, {
            method: 'POST',
            credentials: 'same-origin',
            headers:headers,
            body: querystring.stringify({
                username:user.username,
                password:user.password
            })
        })
            .then( response => response.json())
            .then( json => dispatch( login_receive( user, json )))
    }
}

function should_login (state) {
    return !state.login.isLogin && !state.login.isLogining
}

export function action_logout() {
    return (dispatch) => dispatch(fetch_logout())
}
function logout_result() {
    return{
        type: LOGOUT
    }
}

function fetch_logout () {
    return dispatch => {
        return fetch(`/home/users/logout`, {
            credentials: 'same-origin'
        })
            .then( response => response.json())
            .then(
                json => {
                    if(json.status)
                        return dispatch(logout_result())
                }
            )
    }
}
export const USERINFO_CHANGE = 'USERINFO_CHANGE';
function userinfo_change(userinfo){
    return {
        type: USERINFO_CHANGE,
        userinfo:userinfo
    }
}
let fetch_userinfo_islogin=null;
export function fetch_userinfo ( isLogin ) {
    return (dispatch, getState) => {
        if(isLogin){
            return fetch(`/home/users/userinfo`, {
                    credentials: 'same-origin'
                }).then( response => response.json())
                    .then(
                        json => {
                            return dispatch(userinfo_change(JSON.stringify(json)));
                        }
                    );
        }else{
            return dispatch(userinfo_change(null));
        }
    }
}